package com.firewolf.rbac.security;

import com.firewolf.rbac.mapper.SysRoleMapper;
import com.firewolf.rbac.mapper.SysUserMapper;
import com.firewolf.rbac.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：刘兴
 * 时间:19/3/5
 **/
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserExample sue = new SysUserExample();
        sue.createCriteria().andNameEqualTo(username);
        List<SysUser> sysUsers = sysUserMapper.selectByExample(sue); //查询用户
        if (sysUsers != null && sysUsers.size() > 0) {
            SysUser u = sysUsers.get(0);
            List<GrantedAuthority> authorities = new ArrayList<>();
//            //根据用户ID查询角色
//            List<SysRole> roles = sysRoleMapper.selectRolesByUserId(u.getId());
//            for (SysRole sysRole : roles) {
//                System.out.println("角色---"+sysRole.getName());
//                authorities.add(new SimpleGrantedAuthority(sysRole.getName()));
//            }

            List<String> permissions = sysUserMapper.selectPermissionsByUserId(u.getId());

            permissions.stream().forEach(x -> authorities.add(new SimpleGrantedAuthority(x)));

            User user = new User(u.getName(), u.getPassword(), authorities);
            return user;
        } else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }
}
